#include "leaveapplicationview.h"
#include "sqloperator.h"
#include <QDebug>
#include <QHeaderView>
#include <QDate>
#include <QColor>

LeaveApplicationView::LeaveApplicationView(EmployeeManager *employeeManager, const QString &empId, QWidget *parent) : 
    QWidget(parent),
    m_employeeManager(employeeManager),
    m_empId(empId),
    m_selectedRequestId(-1)
{
    initUI();
    loadLeaveRequests();
}

void LeaveApplicationView::initUI()
{
    // 设置窗口标题
    setWindowTitle("请假申请");
    setMinimumSize(600, 500);

    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    // 创建申请表单区域
    QWidget *formWidget = new QWidget;
    QVBoxLayout *formLayout = new QVBoxLayout(formWidget);

    // 请假类型
    QHBoxLayout *leaveTypeLayout = new QHBoxLayout;
    QLabel *leaveTypeLabel = new QLabel("请假类型:");
    m_leaveTypeComboBox = new QComboBox;
    m_leaveTypeComboBox->addItem("年假");
    m_leaveTypeComboBox->addItem("病假");
    m_leaveTypeComboBox->addItem("事假");
    m_leaveTypeComboBox->addItem("婚假");
    m_leaveTypeComboBox->addItem("产假");
    m_leaveTypeComboBox->addItem("其他");
    leaveTypeLayout->addWidget(leaveTypeLabel);
    leaveTypeLayout->addWidget(m_leaveTypeComboBox);
    formLayout->addLayout(leaveTypeLayout);

    // 开始日期
    QHBoxLayout *startDateLayout = new QHBoxLayout;
    QLabel *startDateLabel = new QLabel("开始日期:");
    m_startDateEdit = new QDateEdit(QDate::currentDate());
    m_startDateEdit->setCalendarPopup(true);
    startDateLayout->addWidget(startDateLabel);
    startDateLayout->addWidget(m_startDateEdit);
    formLayout->addLayout(startDateLayout);

    // 结束日期
    QHBoxLayout *endDateLayout = new QHBoxLayout;
    QLabel *endDateLabel = new QLabel("结束日期:");
    m_endDateEdit = new QDateEdit(QDate::currentDate());
    m_endDateEdit->setCalendarPopup(true);
    endDateLayout->addWidget(endDateLabel);
    endDateLayout->addWidget(m_endDateEdit);
    formLayout->addLayout(endDateLayout);

    // 请假原因
    QHBoxLayout *reasonLayout = new QHBoxLayout;
    QLabel *reasonLabel = new QLabel("请假原因:");
    m_reasonTextEdit = new QTextEdit;
    m_reasonTextEdit->setMinimumHeight(100);
    reasonLayout->addWidget(reasonLabel);
    reasonLayout->addWidget(m_reasonTextEdit);
    formLayout->addLayout(reasonLayout);

    // 按钮布局
    QHBoxLayout *buttonLayout = new QHBoxLayout;
    m_submitButton = new QPushButton("提交申请");
    m_cancelButton = new QPushButton("撤销申请");
    buttonLayout->addWidget(m_submitButton);
    buttonLayout->addWidget(m_cancelButton);
    formLayout->addLayout(buttonLayout);

    // 连接撤销按钮信号槽
    connect(m_submitButton, &QPushButton::clicked, this, &LeaveApplicationView::onSubmitRequest);
    connect(m_cancelButton, &QPushButton::clicked, this, &LeaveApplicationView::onCancelRequest);

    // 状态标签
    m_statusLabel = new QLabel;
    m_statusLabel->setStyleSheet("color: blue;");
    formLayout->addWidget(m_statusLabel);

    mainLayout->addWidget(formWidget);

    // 创建申请历史表格
    m_requestTableWidget = new QTableWidget;
    m_requestTableWidget->setColumnCount(6);
    QStringList headers;
    headers << "申请ID" << "请假类型" << "开始日期" << "结束日期" << "申请时间" << "状态";
    m_requestTableWidget->setHorizontalHeaderLabels(headers);
    m_requestTableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    mainLayout->addWidget(m_requestTableWidget);

    // 连接表格点击信号
    connect(m_requestTableWidget, &QTableWidget::cellClicked, this, &LeaveApplicationView::onRequestTableItemClicked);
}

void LeaveApplicationView::loadLeaveRequests()
{
    if (!m_employeeManager) {
        qDebug() << "EmployeeManager is null";
        return;
    }

    QVariantList requests = m_employeeManager->getLeaveRequests(m_empId);

    // 清空表格
    m_requestTableWidget->setRowCount(0);

    // 填充表格
    foreach (const QVariant &requestVar, requests) {
        QVariantHash request = requestVar.toHash();
        int row = m_requestTableWidget->rowCount();
        m_requestTableWidget->insertRow(row);

        m_requestTableWidget->setItem(row, 0, new QTableWidgetItem(request.value("request_id").toString()));
        m_requestTableWidget->setItem(row, 1, new QTableWidgetItem(request.value("leave_type").toString()));
        m_requestTableWidget->setItem(row, 2, new QTableWidgetItem(request.value("start_date").toString()));
        m_requestTableWidget->setItem(row, 3, new QTableWidgetItem(request.value("end_date").toString()));
        m_requestTableWidget->setItem(row, 4, new QTableWidgetItem(request.value("request_time").toString()));
        m_requestTableWidget->setItem(row, 5, new QTableWidgetItem(request.value("status").toString()));
    }
}

void LeaveApplicationView::onSubmitRequest()
{
    if (!m_employeeManager) {
        m_statusLabel->setText("提交失败: 员工管理器为空");
        m_statusLabel->setStyleSheet("color: red;");
        emit requestSubmitted(false);
        return;
    }

    // 获取表单数据
    QString leaveType = m_leaveTypeComboBox->currentText();
    QString startDate = m_startDateEdit->date().toString("yyyy-MM-dd");
    QString endDate = m_endDateEdit->date().toString("yyyy-MM-dd");
    QString reason = m_reasonTextEdit->toPlainText();

    // 验证输入
    if (reason.isEmpty()) {
        m_statusLabel->setText("请输入请假原因");
        m_statusLabel->setStyleSheet("color: red;");
        return;
    }

    if (QDate::fromString(startDate, "yyyy-MM-dd") > QDate::fromString(endDate, "yyyy-MM-dd")) {
        m_statusLabel->setText("开始日期不能晚于结束日期");
        m_statusLabel->setStyleSheet("color: red;");
        return;
    }

    // 提交申请
    bool success = m_employeeManager->submitLeaveRequest(m_empId, leaveType, startDate, endDate, reason);

    if (success) {
        m_statusLabel->setText("申请提交成功，请等待审核");
        m_statusLabel->setStyleSheet("color: green;");
        m_reasonTextEdit->clear();
        loadLeaveRequests(); // 刷新申请历史
    } else {
        m_statusLabel->setText("申请提交失败，请重试");
        m_statusLabel->setStyleSheet("color: red;");
    }

    emit requestSubmitted(success);
}

void LeaveApplicationView::onCancelRequest()
{
    if (m_selectedRequestId == -1) {
        m_statusLabel->setText("请先选择要撤销的申请");
        m_statusLabel->setStyleSheet("color: red;");
        return;
    }

    if (!m_employeeManager) {
        m_statusLabel->setText("撤销失败: 员工管理器为空");
        m_statusLabel->setStyleSheet("color: red;");
        return;
    }

    // 调用撤销申请方法
    bool success = m_employeeManager->cancelLeaveRequest(m_selectedRequestId);

    if (success) {
        m_statusLabel->setText("申请撤销成功");
        m_statusLabel->setStyleSheet("color: green;");
        m_selectedRequestId = -1; // 重置选中的申请ID
        loadLeaveRequests(); // 刷新申请历史
    } else {
        m_statusLabel->setText("申请撤销失败，请重试");
        m_statusLabel->setStyleSheet("color: red;");
    }
}

void LeaveApplicationView::onRequestTableItemClicked(int row, int column)
{
    Q_UNUSED(column);
    // 获取选中行的申请ID
    QTableWidgetItem *item = m_requestTableWidget->item(row, 0);
    if (item) {
        m_selectedRequestId = item->text().toInt();
        // 高亮选中行
        for (int i = 0; i < m_requestTableWidget->rowCount(); ++i) {
            for (int j = 0; j < m_requestTableWidget->columnCount(); ++j) {
                QTableWidgetItem *tableItem = m_requestTableWidget->item(i, j);
                if (tableItem) {
                    if (i == row) {
                        tableItem->setBackground(QColor(173, 216, 230)); // 浅蓝色背景
                    } else {
                        tableItem->setBackground(QColor(255, 255, 255)); // 白色背景
                    }
                }
            }
        }
    }
}

void LeaveApplicationView::setEmployeeId(const QString &empId)
{
    m_empId = empId;
    loadLeaveRequests(); // 重新加载请假申请数据
}
